<template>
<div id="wrapper">
	<scroller class="content">
		<div class="v-waterfall-content" id="v-waterfall">
				<div
					v-for="(img, index) in waterfallList"
					:key="index"
					class="v-waterfall-item"
					:style="{
						top: img.top + 'px',
						left: img.left + 'px',
						width: waterfallImgWidth + 'px',
						height: img.height,
					}"
				>
					<img :src="img.src" alt="" />
					<p class="title">{{ img.title }}</p>
					<span class="price">{{ img.price }}</span>
					<span class="sale">{{ img.sale }}</span>
				</div>
		</div>
	</scroller>
</div>
</template>

<script>
import {getHomeMultiData,getGoodsData} from 'network/home'; //数据导入
import Scroller from '../../components/common/scroller/Scroller.vue';
	export default {
  components: { Scroller },
		name: "v-waterfall",
		data() {
			return {
        goods:{
          'pop': {page:0,list:[]},
          'new':{page:0,list:[]},
          'sell':{page:0,list:[]}
        },
				waterfallList: [],
				// waterfallImgWidth: 100,
				//waterfallImgWidth: 200,// 每个盒子的宽度
				// waterfallImgCol: 5,// 瀑布流的列数
				waterfallImgCol: 2,// 瀑布流的列数
				waterfallImgRight: 0,// 每个盒子的右padding
				waterfallImgBottom: 0,// 每个盒子的下padding
				waterfallDeviationHeight: [],
				imgList: [],
				title:[],
				price:[],
				sale:[]
			}
		},
		created() {
     	this.getGoodsDatas('pop');
			this.getGoodsDatas('new');
			this.getGoodsDatas('sell');
		},
		mounted() {
			this.$nextTick(function(){ //延时
        setTimeout(() => {
					this.cacheData();
        }, 2000);
      })
			this.$nextTick(function(){ //延时
        setTimeout(() => {
					this.calculationWidth();
        }, 2000);
			})
			this.$nextTick(function(){ //延时
        setTimeout(() => {
					this.height();
        }, 5000);
      })
		},
		prop:{
			data1:{
				type:String,
				default:"pop",
			}
		},
		methods: {
       async getGoodsDatas(type){ //最下面的图片区域数据
        try {
					const page = this.goods[type].page + 1;
					const {data:res} = await getGoodsData(type,page);
					this.goods[type].list = [...this.goods[type].list,...res.list];
					this.goods[type].page += 1;
				} catch (error) {
					console.log('网络检测慢');
				}
			},
			// 缓存不同请求的值
			cacheData(){
				switch('pop'){
					case 'pop': {
						const a = [];
						this.goods.pop.list.map(val=>{
							a.push(val.show.img)
							this.sale.push(val.sale)
							this.title.push(val.title)
							this.price.push(val.price)
						})
						this.imgList = [...a];
						break;
					}
					case 'new':{
						const a = [];
						this.goods[type].list.map(val=>{
							a.push(val.show.img)
							this.sale.push(val.sale)
							this.title.push(val.title)
							this.price.push(val.price)
						})
						this.imgList = [...a];
						break;
					}
					case 'sell':{
						const a = [];
						this.goods[type].list.map(val=>{
							a.push(val.show.img)
							this.sale.push(val.sale)
							this.title.push(val.title)
							this.price.push(val.price)
						})
						this.imgList = [...a];
						break;
					}
				}
			},
			//计算每个图片的宽度或者是列数
			calculationWidth() {
        let domWidth = document.getElementById("v-waterfall").offsetWidth;
				if (!this.waterfallImgWidth && this.waterfallImgCol) {
					this.waterfallImgWidth = (domWidth - this.waterfallImgRight * this.waterfallImgCol) / this.waterfallImgCol;
				} else if (this.waterfallImgWidth && !this.waterfallImgCol) {
					this.waterfallImgCol = Math.floor(domWidth / (this.waterfallImgWidth + this.waterfallImgRight))
				}
				//初始化偏移高度数组
				this.waterfallDeviationHeight = new Array(this.waterfallImgCol);
				for (let i = 0; i < this.waterfallDeviationHeight.length; i++) {
					this.waterfallDeviationHeight[i] = 0;
				}
				this.imgPreloading()
			},
			//图片预加载
			imgPreloading() {
				for (let i = 0; i < this.imgList.length; i++) {
					let aImg = new Image();
					aImg.src = this.imgList[i];
					aImg.onload = aImg.onerror = (e) => {
						let imgData = {};
						imgData.height = this.waterfallImgWidth / aImg.width * aImg.height;
						imgData.src = this.imgList[i];
						imgData.title = this.title[i];// 说明文字（也可以自己写数组，或者封装json数据，都可以，但是前提是你会相关操作，这里不赘述）
						imgData.price = this.price[i];// 说明文字
						imgData.sale = this.sale[i];
						this.waterfallList.push(imgData);
						this.rankImg(imgData);		
					}
				}
			},
			//瀑布流布局
			rankImg(imgData) {
				let {
					waterfallImgWidth,
					waterfallImgRight,
					waterfallImgBottom,
					waterfallDeviationHeight,
					waterfallImgCol
				} = this;
				let minIndex = this.filterMin();
				imgData.top = waterfallDeviationHeight[minIndex];
				imgData.left = minIndex * (waterfallImgRight + waterfallImgWidth);
				// waterfallDeviationHeight[minIndex] += imgData.height + waterfallImgBottom;// 不加文字的盒子高度
				waterfallDeviationHeight[minIndex] += imgData.height + waterfallImgBottom + 56;// 加了文字的盒子高度，留出文字的地方（这里设置56px）
				//console.log(imgData);
			},
			/**
			 * 找到最短的列并返回下标
			 * @returns {number} 下标
			 */
			filterMin() {
				const min = Math.min.apply(null, this.waterfallDeviationHeight);
				return this.waterfallDeviationHeight.indexOf(min);
			},
			height(){
				this.$nextTick(function(){
					var h = document.querySelectorAll(".v-waterfall-item");
					var vh = 0;
					for (let index = 0; index < h.length; index+=2) {
						vh += h[index].offsetHeight;
					}
					document.querySelector("#v-waterfall").style.height = (vh+400)+"px"
				})
        
        //
			}
		}
	}
</script>

<style scoped>
#wrapper{
	height: 100vh;
}
.content{
  height: calc(100% - 44px);
	overflow: hidden;
}
.v-waterfall-content {
  /* 主要 */
  width: 100%;
  position: relative;
  /* 次要：设置滚动条，要求固定高度 */
}

.v-waterfall-item {
  /* 主要 */
  position: absolute;
  padding: 5px;
}

.v-waterfall-item img {
  /* 主要 */
  /* width: auto;height: auto; */
  width: 100%;
  height: auto;
  /* 次要 */
  border-radius: 6px;
}
.title {
  display: inline-block;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.price {
  float: left;
  color: pink;
  font-weight: bold;
}
.sale {
  float: right;
  color: pink;
}
</style>
